package com.power.util;

import org.springframework.util.ObjectUtils;

import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * @Author 海晨忆
 * @Des 缓存工具类
 * @Date 2025/8/14 9:22
 */
public class CacheUtils {
    public static <T> T getCacheData(Supplier<T> cacheSelector, Supplier<T> databaseSelector, Consumer<T> cacheSave) {
        //从缓存读取数据
        T data = cacheSelector.get();
        //没有读到数据，则从数据库中读取
        if (ObjectUtils.isEmpty(data)) {
            data = databaseSelector.get();
            //数据库的数据不是空，则放入缓存中，便于下次读取
            if (!ObjectUtils.isEmpty(data)) {
                cacheSave.accept(data);
            }
        }
        return data;
    }
}
